package com.fadadianqi.mall.product;

import com.fadadianqi.mall.product.model.ItemSPU;
import com.fadadianqi.mall.product.service.ItemSPUService;
import com.fadadianqi.search.AbstractSearcher;
import com.fadadianqi.search.Argument;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.Utils;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.highlight.Highlighter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * Created by aroot on 2/27/14.
 */
@Service
public class SpuSearcher extends AbstractSearcher {

    @Autowired
    private SpuIndexService spuIndexService;

    @Autowired
    private ItemSPUService itemSPUService;

    @Override
    protected Argument initializtionArgument(String keyword, Pagination pagination) {
        Argument argument = Argument.getInstance();
        argument.setPagination(pagination);
        argument.setArgs(SpuIndexService.FIELD_BRAND_NAME, keyword, BooleanClause.Occur.SHOULD, 0.6F);
        argument.setArgs(SpuIndexService.FIELD_DETAILS, keyword, BooleanClause.Occur.SHOULD, 0.6F);
        argument.setArgs(SpuIndexService.FIELD_DISPLAY_NAME, keyword, BooleanClause.Occur.SHOULD, 0.7F);
        argument.setArgs(SpuIndexService.FIELD_NAME, keyword, BooleanClause.Occur.SHOULD, 0.9F);
        if (!Utils.isLetter(keyword)) {
            String pinyin = StringHelper.toPinyin(keyword);
            argument.setArgs("pinyin", pinyin, BooleanClause.Occur.SHOULD, 0.5F);
        } else {
            argument.setArgs("pinyin", keyword, BooleanClause.Occur.SHOULD, 0.5F);
        }
        return argument;
    }

    @Override
    protected Object documentToVO(IndexSearcher searcher, Document doc, Highlighter highlighter) throws IOException {
        String id = doc.get(SpuIndexService.FIELD_ID);
        ItemSPU spu = itemSPUService.getById(id);
        return spu;
    }

    @Override
    protected String getIndexPath() {
        return spuIndexService.getCurrentIndexPath();
    }

}
